<template>
  <div style="width: 97%;margin-left: 10px">
    <TableTemplate
        ref="registerTableRef"
        :data-set="dataSet"
        :loading="loading"
        @select-submit="projectPageAll"
        @reset-submit="reset"
        @handleView="handleView"
        @notificationAdd="notificationAdd"
        @notificationAdds="notificationAdds"
        @Delects="Delects"
        @exportExcel="exportExcel"
        :get-status-color="getStatusColor"
        @deleteId="deleteId"
        @handleEdit="handleEdit"
        @handle-change="handleChange"
    />
    <DialogTemplate
        v-model="dialogTemplateVisible"
        :title="title"
        :is-to-html="true"
        @handleHtmlContent="handleHtmlContent"
        :initial-data="initialData"
        :width="'800px'"
        :form-items="formItems"
        :operation-name="operationName"
        :is-view="isViewMode"
        @handleDialogSubmit="handleDialogSubmit"
        ref="dialogTemplateRef"
    />
    <BatchAddTemplate
        ref="registerDialogRef"
        v-model="batchAddVisible.dialogFormVisibles"
        @submit-adds="batchAddSubmit"
        @notificationAdds="notificationAdds"
        :batch-add-visible="batchAddVisible"
    />
  </div>
</template>
<script setup>
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  cementAdd,
  cementDelects,
  cementEdit,
  cementPage,
  cementTitle,
  exportNotifcationExcel
} from "../management/mangementApi.js"
import {useUserStore} from '@/pinia/stores/user'
import TableTemplate from "@/pages/account/components/tableTemplate.vue";
import DialogTemplate from "@/pages/account/components/dialogTemplate.vue";
import BatchAddTemplate from "@/pages/account/components/batchAddTemplate.vue";
const fileContent = ref('')
const userStore = useUserStore()
const userData = userStore.userInfo
// 刷新loading
const loading = ref(false)
const handleIndex = ref([])
const registerTableRef = ref('')
const title = ref('')
const initialData = ref({})
const dialogTemplateVisible = ref(false)
const dialogTemplateRef = ref('')
const registerDialogRef = ref('')
const isViewMode = ref(false)
const operationName = ref('')
const formItems = ref([{
  list: [
    {
      label: '公告标题',
      prop: 'title',
      type: 'input',
      rules: [{required: true, message: '请输入公告标题', trigger: 'blur'},
        {min: 3, max: 64, message: '公告标题长度3-64位', trigger: 'blur'}
      ],
      placeholder: '请输入公告标题'
    },
    {
      label: '公告内容',
      prop: 'content',
      type: 'textarea',
      rules: [{required: true, message: '请输入公告内容', trigger: 'blur'},
        {min: 3, max: 999, message: '公告内容长度3-64位', trigger: 'blur'}
      ],
      placeholder: '请输入公告内容'
    },
    {
      label: '公告类型',
      prop: 'type',
      type: 'select',
      options: [
        {label: '通知', value: 0},
        {label: '公告', value: 1},
      ],
      rules: [{required: true, message: '请选择公告类型', trigger: 'blur'}],
      placeholder: '请选择公告类型'
    },
    {
      label: '通知类型',
      prop: 'cementTypes',
      type: 'select',
      options: [
        {label: '系统', value: 0},
        {label: '高校', value: 1},
      ],
      rules: [{required: true, message: '请选择通知类型', trigger: 'blur'}],
      placeholder: '请选择通知类型'
    },
    {
      label: '公告图片',
      prop: 'imgUrl',
      type: 'uploadImage',
      multiple: true,
      limit: 1,
      rules: [
        {required: true, message: '请上传公告图片', trigger: 'blur'}
      ],
      placeholder: '请上传公告图片'
    },
    {
      label: '公告附件',
      prop: 'file',
      type: 'uploadFile',
      multiple: true,
      limit: 1,
      fileType: '.docx,.pdf',
      rules: [
        {required: true, message: '请上传公告附件', trigger: 'blur'}
      ],
      placeholder: '请上传公告附件'
    }
  ]
}])
let dataSet = reactive({
  queryBox: [
    {
      model: 'title',
      type: 'input',
      placeholder: '请输入公告名称'
    },
    {
      model: 'userName',
      type: 'input',
      placeholder: '请输入发布人'
    },
    {
      model: 'type',
      type: 'select',
      placeholder: '项目类型',
      options: [
        {label: '通知', value: 0},
        {label: '公告', value: 1},
      ],
    },
    {
      model: 'status',
      type: 'select',
      placeholder: '公告状态',
      options: [
        {label: '启用', value: 0},
        {label: '禁用', value: 1},
      ]
    }
  ],
  tableList: [
    {prop: 'title', label: '公告标题', width: '180'},
    {prop: 'cementType', label: '公告类型', width: '180'},
    {prop: 'content', label: '公告内容', width: '180'},
    {prop: 'userName', label: '发布人', width: '180'},
    {prop: 'createTime', label: '发布时间', width: '180'},
  ],
  tnQueryTop: [
    {name: '新增', click: 'notificationAdd', type: 'primary'},
    {name: '批量新增', click: 'notificationAdds', type: 'danger'},
    {name: '批量删除', click: 'Delects', type: 'warning'},
    {name: '导出', click: 'exportExcel', type: 'info'},
  ],
  tableListStutas: [
    {prop: 'statuss', label: '公告状态', width: '100', stutasColor: 'danger'},
  ],
  tableListImages: [
    {prop: 'imgUrl', label: '公告封面', width: '100'},
  ],
  operationBtns: [
    {name: '编辑', click: 'handleEdit', type: 'primary'},
    {name: '详情', click: 'handleView', type: 'info'},
    {name: '删除', click: 'deleteId', type: 'danger'},
  ],
  tableData: {
    total: 0,
    rows: []
  }
})
//批量新增弹窗引用
let batchAddVisible = reactive({
  fileName: '公告批量新增模板.xlsx',
  dialogFormVisibles: false,
})
//公告状态
const getStatusColor = (statuss) => {
  switch (statuss) {
    case '禁用':
      return 'primary';
    default:
      return 'success';
  }
};
// 查询列表
const projectPageAll = async (data) => {
  loading.value = true
  await cementPage(data).then(datas => {
    dataSet.tableData.rows = datas.data.records
    dataSet.tableData.total = datas.data.total
  }).finally(() => {
    loading.value = false
  })

}
// 重置
const reset = (data) => {
  projectPageAll(data)
}
// 选中的数据
const handleChange = (data) => {
  handleIndex.value = data
}

// 删除
const deleteId = async (data) => {
  let datas = await cementDelects([data.id])
  if (datas.code === 0) {
    ElMessage.success("删除成功")
    projectPageAll();
  } else {
    ElMessage.error("删除失败")
  }
}
// 批量删除
const Delects = () => {
  if (handleIndex.value.length === 0) {
    ElMessage.error('请至少选择一条数据！')
    return;
  }
  ElMessageBox.confirm(
      '确定要删除这些项目吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const ids = handleIndex.value.map(item => item.id)
    await cementDelects(ids).then(response => {
      if (response.code === 0) {
        ElMessage.success('删除成功')
        registerTableRef.value?.clearSelection();
        projectPageAll({});
      } else {
        ElMessage.error('删除失败')
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
    registerTableRef.value?.clearSelection();
  })
}
// 导出
const exportExcel = () => {
  if (handleIndex.value<1){
    ElMessage.error("请选择要导出的数据！")
    return
  }
  exportNotifcationExcel(handleIndex.value);
  ElMessage.success("导出成功")
}
// 新增
const notificationAdd = () => {
  operationName.value = '新增'
  title.value = '新增公告'
  isViewMode.value = false
  initialData.value = {}
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}

// 批量新增
const notificationAdds = async () => {
  batchAddVisible.dialogFormVisibles = true
}
// 批量新增提交
const batchAddSubmit = async (fileList, username) => {
  // 必须包含的字段
  const requiredFields = ["公告标题", "公告内容", "公告类型"];
  // 检查 fileList 的字段
  const isValidFile = fileList.every(item =>
      requiredFields.every(field => Object.prototype.hasOwnProperty.call(item, field))
  );
  if (!isValidFile) {
    ElMessage.error("文件格式错误，请上传正确的模板文件！");
    return;
  }
  const fromData = fileList.map(item => ({
    title: item.公告标题,
    content: item.公告内容,
    type: item.公告类型 === '公告' ? 1 : 0,
    userId: userData.id,
    cementTypes: 0,
  }))
  if (fromData.length < 1) {
    ElMessage.error("文件内容为空，请检查模板文件！");
    return;
  }
  for (let i = 0; i < fromData.length; i++) {
    await cementTitle(fromData[i].title).then(async res => {
      if (res.code === 1) {
        ElMessage.error("新增的文件中有公告或通知已存在！")
        return;
      }
    });
  }
  await cementAdd(fromData).then(res => {
    if (res.code === 0) {
      ElMessage.success("新增成功")
      batchAddVisible.dialogFormVisibles = false
      projectPageAll({});
    }
  }).catch(res => {
    ElMessage.error("新增失败")
  })
}
//编辑
const handleEdit = (data) => {
  operationName.value = '编辑'
  title.value = '编辑公告'
  isViewMode.value = false
  initialData.value = {...data}
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 查看详情
const handleView = (data) => {
  operationName.value = '详情'
  title.value = '公告详情'
  isViewMode.value = true
  initialData.value = {...data}
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 弹窗提交
const handleDialogSubmit = async (data) => {
  let response;
  if (fileContent.value!==''){
    data.fileContent = fileContent.value
  }
  if (operationName.value === '新增') {
    await cementTitle(data.title).then(async res => {
      if (res.code === 0) {
        data.userId = userData.id;
        await cementAdd([data]).then(res => {
          if (res.code === 0) {
            ElMessage.success("新增成功")
            dialogTemplateVisible.value = false;
            projectPageAll({});
          }
        }).catch(res => {
          ElMessage.error("新增失败")
        })
      } else {
        ElMessage.error(res.data.message)
      }
    }).catch(res => {
      ElMessage.error(res.data.message)
    })
  } else if (operationName.value === '编辑') {
    await cementEdit(data).then(res => {
      if (res.code === 0) {
        ElMessage.success("修改成功")
        dialogTemplateVisible.value = false;
        projectPageAll({});
      }
    }).catch(res => {
      ElMessage.error("修改失败")
    })
  }
}

const handleHtmlContent = (data) => {
  fileContent.value = data
}

onMounted(() => {
  projectPageAll({})
});
</script>
<style>
.search-title {
  background: white;
  padding: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
}


.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style scoped>
.demo-pagination-block {
  margin-top: 10px;
}

.dialog img {
  width: 720px;
  height: 400px;
}

.el-icon .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}

.avatar-uploader img {
  width: 50%;
  height: 50%;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
</style>
